<template>
  <div class="msg-wrapper">
    <MessageList :msgs="msgs" :no-more="noMore" :direction="direction" :reply-msgs-map="replyMsg" />
    <MessageInput :sessionId="sessionId" :reply-msgs-map="replyMsg" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, computed, ref, reactive, onUnmounted, watch } from 'vue'
import MessageList from './message-list.vue'
import MessageInput from './message-input.vue'
import { deepClone } from '../../../utils'
import store from '@/store'
import { downVideo } from '../../../api/index'
import { events } from '../../../utils/constants'
// import wx from 'weixin-js-sdk';
import bus from '@/utils/bus'

const props = defineProps(['sessionId'])
const msgs = ref([])
const replyMsg = reactive({})
const noMore = ref(false)

watch(
  () => props.sessionId,
  (id) => {
    getMsgList(id).then((list) => {
      // getReplyMsg(list)
      // getIsPeerRead(list)

      console.log(list)
      direction.value = 0
      msgs.value = list
    })
  }
)

const direction = ref(0)

const getMsgList = (id) => {
  return new Promise((resolve, reject) => {
    const params = {
      conversationId: id,
      limit: 50,
      direction: 0
    }

    uni.$nim.V2NIMMessageService.getMessageList(params).then((list) => {
      const arr = list.reverse()
      if (list.length < 50) {
        noMore.value = true
      } else {
        noMore.value = false
      }

      resolve(arr)
    })
  })
}

// watch(
//   () => store.state.im.connectStatus,
//   (status) => {
//     console.log(status)
//     if (status == 1) {
//       // 连接
//       getMsgList(props.sessionId).then((list) => {
//         console.log(list)
//         direction.value = 0
//         msgs.value = list
//       })
//     } else if (status == 2) {
//       // 重连
//     } else {
//       // 断开
//     }
//   }
// )

const loadMore = (id, anchor) => {
  return new Promise((resolve, reject) => {
    const params = {
      conversationId: id,
      limit: 50,
      anchorMessage: anchor,
      direction: 0
    }

    uni.$nim.V2NIMMessageService.getMessageList(params).then((list) => {
      list = list.reverse()
      if (list.length < 50) {
        noMore.value = true
      } else {
        noMore.value = false
      }

      resolve(list)
    })
  })
}

const getReplyMsg = (list) => {
  console.log(list)
  const keys = new Set()

  list.map((v) => {
    if (v.serverExtension) {
      const { yxReplyMsg } = JSON.parse(v.serverExtension)

      v['ReplyMessageClientId'] = yxReplyMsg.idClient
      keys.add(yxReplyMsg.idClient)
    }
    // if (v.threadReply) {
    //   v['ReplyMessageClientId'] = v.threadReply.messageClientId
    //   keys.add(v.threadReply.messageClientId)
    // }
    // if (v.threadRoot) {
    //   keys.add(v.threadRoot.messageClientId)
    // }
  })

  list.find((v) => {
    if (keys.size) {
      if (keys.has(v.messageClientId)) {
        replyMsg[v.messageClientId] = v
        keys.delete(v.messageClientId)
      }
    } else {
      return true
    }
  })

  if (keys.size) {
    uni.$nim.V2NIMMessageService.getMessageListByIds(Array.from(keys)).then((res) => {
      res.find((v) => {
        if (keys.has(v.messageClientId)) {
          replyMsg[v.messageClientId] = v
          keys.delete(v.messageClientId)
        } else {
          return true
        }
        console.log(replyMsg)
      })
    })
  } else {
    console.log(replyMsg)
  }
}

// const getIsPeerRead = (list) => {
//   const scene = props.sessionId.split('|')[1]
//   const f = list.filter((v) => {
//     return v.isSelf === false
//   })
//   console.log(f)
//   if (scene === '1') {
//     f.map((v) => {
//       uni.$nim.V2NIMMessageService.sendP2PMessageReceipt(v)
//     })
//   } else if (scene === '2') {
//     uni.$nim.V2NIMMessageService.sendTeamMessageReceipts(f)
//   }
// }

const videoFrom = ref('')
const localId = ref('')
const localSrc = ref('')
let innerAudioContext = null

const downloadVideo = async (id) => {
  try {
    const res = await downVideo(id)
    if (res.data.audioUrl) {
      videoFrom.value = 'oos'
      localSrc.value = res.data.audioUrl
      playVideo()
    } else {
      videoFrom.value = 'weixin'
      wx.downloadVoice({
        serverId: id, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: function (res) {
          localId.value = res.localId // 返回音频的本地ID
          playVideo(id)
        },
        fail: function (res) {
          uni.showToast({
            title: '上传文件已损坏！',
            icon: 'error',
            duration: 2000
          })
          store.commit('im/VIDEO_PALY', {
            status: 'stop'
          })
        }
      })
    }
  } catch (e) {
    uni.showToast({
      title: '下载语音失败，请检查网络后再尝试',
      icon: 'error',
      duration: 2000
    })
    store.commit('im/VIDEO_PALY', {
      status: 'stop'
    })
  }
}

const playVideo = (id) => {
  if (videoFrom.value === 'weixin') {
    wx.playVoice({
      localId: localId.value, // 需要播放的音频的本地ID，由stopRecord接口获得
      success: function (res) {
        store.commit('im/VIDEO_PALY', {
          id: id,
          status: 'paying'
        })
      }
    })
  } else {
    innerAudioContext = uni.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = localSrc.value
    innerAudioContext.onPlay(() => {
      store.commit('im/VIDEO_PALY', {
        status: 'paying'
      })
    })
    innerAudioContext.onEnded((res) => {
      store.commit('im/VIDEO_PALY', {
        status: 'stop'
      })
      innerAudioContext.destroy()
      innerAudioContext = null
    })
    innerAudioContext.onError((res) => {
      store.commit('im/VIDEO_PALY', {
        status: 'stop'
      })
      innerAudioContext.destroy()
      innerAudioContext = null
    })
  }
}

let isMounted = false

const loadingMore = ref(false)

const videoStopPaly = (e) => {
  store.commit('im/VIDEO_STOP')
}

onMounted(() => {
  uni.$nim.V2NIMMessageService.on('onReceiveMessages', function (res) {
    console.log('onReceiveMessages', res)
    res.map((v) => {
      if (v.conversationId === props.sessionId) {
        const index = msgs.value.findIndex((u) => {
          return u.messageClientId === res.messageClientId
        })
        if (index > -1) {
          msgs.value[index] = v
        } else {
          // getReplyMsg([v])
          msgs.value.push(v)

          bus.emit('clearUnread')
        }
        // getIsPeerRead([v])
      }
    })
  })

  uni.$nim.V2NIMMessageService.on('onSendMessage', function (res) {
    console.log('onSendMessage', res)
    if (res.conversationId === props.sessionId) {
      const index = msgs.value.findIndex((u) => {
        return u.messageClientId === res.messageClientId
      })
      console.log(index)
      if (index > -1) {
        msgs.value[index] = res
      } else {
        // getReplyMsg([res])
        msgs.value.push(res)
      }
      // getIsPeerRead([res])
    }
  })

  uni.$on('onDeleteMessage', (msg) => {
    const index = msgs.value.findIndex((v) => {
      return v.messageClientId === msg.messageClientId
    })

    msgs.value.splice(index, 1)
  })

  uni.$on(events.GET_HISTORY_MSG, (msg) => {
    loadMore(props.sessionId, msg).then((list) => {
      console.log(list)
      if (list.length) {
        direction.value = 1
        msgs.value = [...list, ...msgs.value]
      }
    })
  })
})

onUnmounted(() => {
  uni.$nim.V2NIMMessageService.off('onSendMessage')
  uni.$nim.V2NIMMessageService.off('onReceiveMessages')

  uni.$off('onDeleteMessage')
  uni.$off(events.GET_HISTORY_MSG)
  // bus.off('im_video_stop_paly', videoStopPaly)

  if (innerAudioContext) {
    innerAudioContext.pause()
    innerAudioContext.destroy()
    innerAudioContext = null
    localSrc.value = ''
  }
  if (localId.value) {
    wx.stopVoice({
      localId: localId.value // 需要停止的音频的本地ID，由stopRecord接口获得
    })
    localId.value = ''
  }
  store.commit('im/VIDEO_PALY', {
    id: '',
    status: ''
  })
})
</script>

<style scoped lang="scss">
@import '../../styles/common.scss';

.msg-wrapper {
  display: flex;
  flex-direction: column;
}
</style>
